<template>
  <view class="order-submit-page">
    <!-- 地址选择 -->
    <view class="address-section" @click="chooseAddress">
      <view v-if="address">
        <view class="address-top">
          <text class="address-name">{{ address.name }}</text>
          <text class="address-phone">{{ address.phone }}</text>
        </view>
        <view class="address-detail">{{ address.fullAddress }}</view>
      </view>
      <view v-else class="address-empty">
        <text>新增收货地址</text>
      </view>
      <view class="address-arrow">›</view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-section">
      <view v-for="item in goodsList" :key="item.id" class="goods-item">
        <image :src="item.productImage || '/static/images/shopping/购物车点击前.png'" class="goods-img" />
        <view class="goods-info">
          <view class="goods-title">{{ item.productName || item.name }}</view>
          <view class="goods-price-row">
            <text class="goods-price">￥{{ item.price }}</text>
            <text class="goods-quantity">x{{ item.quantity }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 金额明细 -->
    <view class="discount-section">
      <view class="discount-row">
        <text>商品金额</text>
        <text>￥{{ goodsAmount }}</text>
      </view>
      <view class="discount-row">
        <text>优惠券</text>
        <text>暂无优惠</text>
      </view>
      <view class="discount-row">
        <text>配送费</text>
        <text>￥0</text>
      </view>
      <view class="discount-row total">
        <text>应付金额</text>
        <text class="total-price">￥{{ totalPrice }}</text>
      </view>
    </view>

    <!-- 底部栏 -->
    <view class="order-bottom-bar">
      <view class="order-total">应付：￥{{ totalPrice }}</view>
      <button class="submit-btn" @click="showPayPopup = true">去支付</button>
    </view>
    <!-- 支付方式弹窗 -->
    <view v-if="showPayPopup" class="pay-popup-mask" @click="showPayPopup = false">
      <view class="pay-popup" @click.stop>
        <view class="pay-title">请选择支付方式</view>
        <button class="pay-btn" @click="payNow">立即支付</button>
        <button class="pay-btn wait" @click="waitPay">等待支付</button>
        <button class="pay-cancel" @click="showPayPopup = false">取消</button>
      </view>
    </view>
  </view>
</template>

<script>
import { getUserAddress } from '@/api/address'
import { createOrder } from '@/api/order'
export default {
  data() {
    return {
      address: null,
      goodsList: [],
      goodsAmount: 0,
      totalPrice: 0,
      showPayPopup: false
    }
  },
  onLoad() {
    // 接收购物车页面传递的商品列表
    const eventChannel = this.getOpenerEventChannel && this.getOpenerEventChannel();
    if (eventChannel) {
      eventChannel.on('acceptGoodsList', (data) => {
        if (data && data.goodsList) {
          this.goodsList = data.goodsList;
          this.calcTotal();
        }
      });
    }
    this.loadAddress(); // 只在首次加载时请求默认地址
  },
  methods: {
    loadAddress() {
      const userId = this.$store.state.user.id || uni.getStorageSync('userId');
      if (!userId) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        return;
      }
      getUserAddress(userId).then(res => {
        if (res.code === 200 && res.data && res.data.length > 0) {
          const addr = res.data[0];
          this.address = {
            name: addr.name,
            phone: addr.phone,
            fullAddress: `${addr.province || ''}${addr.city || ''}${addr.district || ''}${addr.detail || ''}`
          };
        } else {
          this.address = null;
        }
      }).catch(() => {
        this.address = null;
      });
    },
    calcTotal() {
      this.goodsAmount = this.goodsList.reduce((sum, item) => sum + (item.price * item.quantity), 0);
      this.totalPrice = this.goodsAmount; // 可加上配送费、减去优惠等
    },
    chooseAddress() {
      uni.navigateTo({
        url: '/pages/address/list',
        events: {
          addressSelected: (addr) => {
            this.address = {
              name: addr.name,
              phone: addr.phone,
              fullAddress: `${addr.province || ''}${addr.city || ''}${addr.district || ''}${addr.detail || ''}`
            };
          }
        }
      });
    },
    submitOrder() {
      uni.showToast({ title: '提交订单功能待开发', icon: 'none' });
    },
    payNow() {
      this.showPayPopup = false;
      uni.showToast({ title: '立即支付功能待开发', icon: 'none' });
    },
    waitPay() {
      this.showPayPopup = false;
      // 组装订单参数
      if (!this.address) {
        uni.showToast({ title: '请选择收货地址', icon: 'none' });
        return;
      }
      if (!this.goodsList.length) {
        uni.showToast({ title: '无商品可下单', icon: 'none' });
        return;
      }
      const userId = this.$store.state.user.id || uni.getStorageSync('userId');
      if (!userId) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        return;
      }
      
      const orderData = {
        userId: userId,
        totalAmount: this.goodsAmount,
        payAmount: this.totalPrice,
        consigneeName: this.address.name,
        consigneePhone: this.address.phone,
        consigneeProvince: this.address.fullAddress.split(/省|市|区|县/)[0] || '',
        consigneeCity: this.address.fullAddress.split(/省|市|区|县/)[1] || '',
        consigneeRegion: this.address.fullAddress.split(/省|市|区|县/)[2] || '',
        consigneeStreet: '',
        consigneeDetail: this.address.fullAddress,
        orderItemList: this.goodsList.map(item => ({
          productId: item.productId || item.id,
          productName: item.productName || item.name,
          salePrice: item.price,
          quantity: item.quantity,
          discountAmount: 0.00,
          adjustAmount: 0.00,
          realPrice: item.price * item.quantity
        }))
      };
      createOrder(orderData).then(res => {
        if (res.code === 200) {
          // 下单成功后删除购物车中已结算的商品
          const cartIds = this.goodsList.map(item => item.cartId || item.id).filter(Boolean);
          if (cartIds.length) {
            // 支持批量删除
            this.$api.deleteCart({ ids: cartIds }).then(() => {
              // 可选：刷新购物车页面或通知其他页面
            });
          }
          uni.showToast({ title: '订单已生成，等待支付', icon: 'success' });
          setTimeout(() => {
            uni.switchTab({ url: '/pages/mine/index' });
          }, 800);
          // 可跳转到订单详情页
        } else {
          uni.showToast({ title: res.msg || '下单失败', icon: 'none' });
        }
      }).catch(() => {
        uni.showToast({ title: '下单失败', icon: 'none' });
      });
    }
  }
}
</script>

<style scoped>
.order-submit-page { background: #fafafa; min-height: 100vh; padding-bottom: 120rpx; }
.address-section { background: #ff5a5f; color: #fff; padding: 32rpx 24rpx 24rpx 24rpx; border-radius: 0 0 24rpx 24rpx; margin-bottom: 18rpx; position: relative; }
.address-top { font-size: 32rpx; font-weight: bold; }
.address-phone { margin-left: 32rpx; }
.address-detail { color: #fff; font-size: 26rpx; margin-top: 8rpx; }
.address-empty { color: #fff; font-size: 28rpx; }
.address-arrow { position: absolute; right: 24rpx; top: 50%; transform: translateY(-50%); font-size: 40rpx; color: #fff; }
.goods-section { background: #fff; border-radius: 12rpx; margin-bottom: 18rpx; }
.goods-item { display: flex; padding: 18rpx 24rpx; border-bottom: 1px solid #f2f2f2; }
.goods-img { width: 120rpx; height: 120rpx; border-radius: 8rpx; margin-right: 18rpx; background: #f5f5f5; }
.goods-info { flex: 1; }
.goods-title { font-size: 30rpx; font-weight: 500; }
.goods-sku { color: #888; font-size: 24rpx; margin: 8rpx 0; }
.goods-price-row { display: flex; align-items: center; }
.goods-price { color: #e93b3d; font-size: 32rpx; font-weight: bold; }
.goods-quantity { margin-left: 18rpx; color: #888; }
.discount-section { background: #fff; border-radius: 12rpx; padding: 18rpx 24rpx; margin-bottom: 120rpx; }
.discount-row { display: flex; justify-content: space-between; font-size: 28rpx; margin-bottom: 12rpx; }
.total { font-weight: bold; }
.total-price { color: #e93b3d; font-size: 36rpx; }
.order-bottom-bar { position: fixed; left: 0; right: 0; bottom: 0; background: #fff; display: flex; align-items: center; justify-content: space-between; padding: 18rpx 24rpx; box-shadow: 0 -2rpx 12rpx #eee; z-index: 10; }
.order-total { font-size: 36rpx; color: #e93b3d; font-weight: bold; }
.submit-btn { background: linear-gradient(90deg, #ff5000, #ff9000); color: #fff; font-size: 32rpx; border-radius: 32rpx; padding: 0 48rpx; }
.pay-popup-mask {
  position: fixed;
  left: 0; right: 0; top: 0; bottom: 0;
  background: rgba(0,0,0,0.3);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}
.pay-popup {
  background: #fff;
  border-radius: 18rpx;
  padding: 48rpx 36rpx 36rpx 36rpx;
  min-width: 400rpx;
  box-shadow: 0 8rpx 32rpx #0001;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.pay-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 36rpx;
}
.pay-btn {
  width: 260rpx;
  margin: 12rpx 0;
  background: linear-gradient(90deg, #ff5000, #ff9000);
  color: #fff;
  font-size: 30rpx;
  border-radius: 32rpx;
  padding: 16rpx 0;
}
.pay-btn.wait {
  background: #f5f5f5;
  color: #ff9000;
  border: 1rpx solid #ff9000;
}
.pay-cancel {
  margin-top: 18rpx;
  color: #888;
  background: none;
  border: none;
  font-size: 28rpx;
}
</style> 